<template>

  <el-row :gutter="20" class="toolbar">
    <el-col :span="2">
      <el-button type="success" @click="addUser" :icon="Plus" title="新增"/>
    </el-col>
    <el-col :span="22">
        <!-- 多条件表单 -->
  <el-form :inline="true" :model="searchUserForm" label-width="auto">
    <el-form-item label="员工编号">
      <el-input clearable v-model="searchUserForm.userNum" />
    </el-form-item>
    <el-form-item label="员工名称">
      <el-input clearable v-model="searchUserForm.userName" />
    </el-form-item>
    <el-form-item label="角色">
        <el-select
          v-model="roleValue"
          clearable
          placeholder="选择角色"
          style="width: 240px"
        >
          <el-option
            v-for="item in roleOptions"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          />
        </el-select>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="selectUser">查询</el-button>
    </el-form-item>
  </el-form>
    </el-col>
  </el-row>



  <!-- 用户管理表格 -->
  <el-table :data="showUserTabel" style="width: 100%">
    <el-table-column prop="date" label="#" width="180" />
    <div>
      <el-checkbox v-model="checked1" size="large" />
      <el-checkbox v-model="checked2" size="large" />
    </div>
    <el-table-column prop="userNum" label="员工编号" width="180" />
    <el-table-column prop="name" label="员工名称" width="180" />
    <el-table-column prop="role" label="角色" width="180" >
      <template #default="scope">
        <span>{{getRoleNames(scope.row.role)}}</span>
      </template>
    </el-table-column>
    <el-table-column prop="gender" label="性别" width="180" >
      <template #default="scope">
        <span>{{scope.row.gender ===1 ? '男' : scope.row.gender === 2 ?  '女' : '未知'}}</span>
      </template>
    </el-table-column>
    <el-table-column prop="phone" label="联系方式" width="180" />
    <el-table-column prop="isValid" label="是否有效" width="180" />
    <el-table-column prop="action" label="操作" width="180">
      <template #default="scope">
        <el-button type="normal" @click="editUser" :icon="Edit" title="编辑"/>
        <el-button type="danger" @click="deleteUser(scope.row.id)" :icon="Delete" title="删除"/>
      </template>
    </el-table-column>
  </el-table>

  <!-- 新增或修改 -->
  <el-dialog
    v-model="dialogVisible"
    :title= "dialogTitle"
    width="500"
  >
    <span>
    <el-form :inline="true" :model="addOrUpdateUserForm" label-width="auto">
    <el-form-item label="用户名">
      <el-input clearable v-model="addOrUpdateUserForm.username" />
    </el-form-item>
    <el-form-item label="密码">
      <el-input clearable v-model="addOrUpdateUserForm.password" />
    </el-form-item>
    <el-form-item label="员工名称">
      <el-input clearable v-model="addOrUpdateUserForm.name" />
    </el-form-item>
    <el-form-item label="手机号">
      <el-input clearable v-model="addOrUpdateUserForm.phone" />
    </el-form-item>
        <el-form-item label="性别">
        <el-select
          v-model="genderValue"
          clearable
          placeholder="选择性别"
          style="width: 240px"
        >
          <el-option
            v-for="item in genderOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
    </el-form-item>
    <el-form-item label="角色">
        <el-select
          v-model="dialogRoleValue"
          clearable
          multiple  
          placeholder="选择角色"
          style="width: 240px"
        >
          <el-option
            v-for="item in roleOptions"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          />
        </el-select>
    </el-form-item>
    </el-form>
    </span>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="save">
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 分页组件 -->
   <el-pagination
      :page-sizes="[5, 10, 20, 30]"
      :size="size"
      :disabled="disabled"
      :background="background"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
</template>

<script setup>
import { computed, onMounted, ref } from 'vue'
import { userPageApi } from '@/api/user.js'
import { getAllRoleApi } from '@/api/role.js'
import { deleteUserApi } from '@/api/user.js'
import { ElMessage ,ElMessageBox } from 'element-plus'
import { addUserApi } from '../../api/user'

import { Edit, Delete ,Plus } from '@element-plus/icons-vue'
// 多条件表单
const searchUserForm = ref({
  userNum: '',
  userName: '',
})
//用户管理表格
const showUserTabel = ref([])
const checked1 = ref(true)
const checked2 = ref(false)
// const pageParams = ref({
//   pageNum:1,
//   pageSize:5,
//   userNum:searchUserForm.value.userNum,
//   userName:searchUserForm.value.userName,
//   role:searchUserForm.value.role
// })
const pageParams = computed(()=>({
  pageNum:1,
  pageSize:10,
  userNum:searchUserForm.value.userNum,
  userName:searchUserForm.value.userName,
  roleId:roleValue.value
}))

//角色回显
const getRoleNames = (roles)=>{
  if(!roles||!Array.isArray(roles)||roles.length===0){
    return '无角色'
  }
  return roles.map(role=>role.roleName).join(',')
}

//角色列表下拉框
const roleOptions = ref([])
const roleValue = ref('')
//分页函数
const userPage =async ()=>{
  let result = (await userPageApi(pageParams.value))
  total.value = result.data.total
  console.log(total)
  showUserTabel.value = result.data.records
}
//获取角色列表
const getAllRole = async ()=>{
  let result = await getAllRoleApi()
  roleOptions.value = result.data
}
const selectUser =()=>{
  userPage()
}
//分页组件
const total = ref([])
const handleSizeChange = (val) => {
  pageParams.value.pageSize = val
  pageParams.value.pageNum = 1
  userPage()
}
const handleCurrentChange = (val) => {
  pageParams.value.pageNum = val
  userPage()
}

//新增或修改表单
const dialogRoleValue = ref([])
const addOrUpdateUserForm = ref({
  username:'',
  password:'',
  name:'',
  gender:'',
  phone:'',
  roleId:''
})

const initAddOrUpdateUserForm = ()=>{
  addOrUpdateUserForm.value={
    username:'',
    password:'',
    name:'',
    gender:'',
    phone:'',
    roleId:''
  }
}



//性别下拉框
const genderValue = ref()
const genderOptions = ref([
  {
  value:1,
  label:'男'
  },
  {
  value:2,
  label:'女'
  }
])

//新增或修改对话框
const dialogVisible = ref(false)
const dialogType = ref('add')

const dialogTitle = computed(()=>{
  return dialogType.value === 'add' ? '新增用户' : '编辑用户'
})



const addUser = ()=>{
  dialogType.value = 'add'
  dialogVisible.value = true
  initAddOrUpdateUserForm
}

const editUser = ()=>{
  dialogType.value = 'edit'
  dialogVisible.value = true
  initAddOrUpdateUserForm
}

const save=async ()=>{
  addOrUpdateUserForm.value.gender = genderValue.value
  if(dialogType.value=='add'){
    addOrUpdateUserForm.value.roleId = dialogRoleValue.value
    try{
      let result = await addUserApi(addOrUpdateUserForm.value)
      if(result.code === 1){
        ElMessage.success("添加成功！")
        dialogVisible.value = false
        userPage()
      }else{
        ElMessage.error("添加失败！")
        dialogVisible.value = false
      }

    }catch(error){
    // 用户点击取消或出现错误
    if (error === 'cancel' || error === 'close') {
      ElMessage.info('已取消新增')
      }else{
        ElMessage.error('新增失败:'+(error.message||'网络错误'))
      }
    }
  }
  if(dialogType.value=='edit'){
    try{
      let result = await updateUserApi(addOrUpdateUserForm.value)
      if(result.code === 1){
        ElMessage.success("修改成功！")
      }else{
        ElMessage.error("修改失败！")
      }
    }catch(error){
    // 用户点击取消或出现错误
    if (error === 'cancel' || error === 'close') {
      ElMessage.info('已取消修改')
      }else{
        ElMessage.error('修改失败:'+(error.message||'网络错误'))
      }
    }
  }
}

//删除

const deleteUser = async (id)=>{
  try{
        // 显示确认对话框
    await ElMessageBox.confirm(
      '确定要删除该用户吗？此操作不可恢复',
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true  // 居中显示
      }
    )
      let result =await deleteUserApi(id)
      if(result.code===1){
        ElMessage.success('删除成功')
          userPage()
      }else{
        ElMessage.error('删除失败')
      }
  }catch(error){
        // 用户点击取消或出现错误
    if (error === 'cancel' || error === 'close') {
      ElMessage.info('已取消删除')
      }else{
            ElMessage.error('删除失败:'+(error.message||'网络错误'))
      }
  }

}

//钩子
onMounted(()=>{
  userPage()
  getAllRole()
})
</script>

<style scoped>
</style>